package com.hx.zhg.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * SSH连接服务器工具类
 */
public class SshUtil {

    protected StringBuffer stdout;
    protected StringBuffer stderr;
    protected Connection con;
    protected Session session;


    public void finalize() {

        this.logout();
    }

    public void logout() {

        if (session != null) {

            session.close();
            session = null;
        }

        if (con != null) {

            con.close();
            con = null;
        }
    }

    public boolean login(String host, String username, String password) throws Exception {

        try {
            this.logout();
            con = new Connection(host);
            con.connect();

            if (!con.authenticateWithPassword(username, password)) {

                throw new Exception("SSH授权验证失败,[username:" + username + ", password:" + password + "]");
            }

            session = con.openSession();

        } catch (Exception e) {

            e.printStackTrace();
            throw e;
        }

        return true;
    }

    public boolean login(String host, String username, String password, int port) throws IOException {

        try {
            this.logout();
            con = new Connection(host, port);
            con.connect();

            if (!con.authenticateWithPassword(username, password)) {

                throw new IOException("SSH授权验证失败,[username:" + username + "password:" + password + "]");
            }

            session = con.openSession();

        } catch (IOException e) {

            e.printStackTrace();
            throw e;
        }

        return true;
    }


    public boolean execute(String command) throws IOException {

        try {
            session = con.openSession();
            session.execCommand(command);
            System.out.println("execute command under SSH : " + command);

            //获取标准输出
            stdout = this.getOutputBuffer(session.getStdout());

            //获取错误输出
            stderr = this.getOutputBuffer(session.getStderr());

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw e;
        }

        return this.isSuccess();
    }

    protected StringBuffer getOutputBuffer(InputStream out) throws IOException {

        InputStream stdoutInputStream = new StreamGobbler(out);

        BufferedReader br = new BufferedReader(new InputStreamReader(stdoutInputStream));

        StringBuffer stdout = new StringBuffer();

        while (true) {

            String line = br.readLine();
            if (line == null) {
                break;
            }
            stdout.append(line + "\n");
        }

        return stdout;
    }

    protected boolean isSuccess() {

        if (stderr != null && stderr.length() > 0) {

            return false;
        }

        return true;
    }

    /**
     * @return the con
     */
    public Connection getConnection() {
        return this.con;
    }

    /**
     * @param con the con to set
     */
    public void setConnection(Connection con) {

        this.logout();
        this.con = con;
    }

    /**
     * @return the stdout
     */
    public StringBuffer getStdout() {
        return this.stdout;
    }

    /**
     * @return the stderr
     */
    public StringBuffer getStderr() {
        return this.stderr;
    }

}
